package com.yeshine.opendata.controller.front.front;

import com.yeshine.opendata.controller.front.AbstractFrontControllerBase;
import com.yeshine.opendata.entity.DataSet;
import com.yeshine.opendata.entity.Org;
import com.yeshine.opendata.service.IDataSetService;
import com.yeshine.opendata.service.IOrgService;
import com.yeshine.opendata.utils.PageResult;
import com.yeshine.opendata.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * Created by taohj on 2014/7/7.
 */

@Controller
@RequestMapping("/front/front/org")
public class OrgController extends AbstractFrontControllerBase {

    @Autowired
    private IOrgService service;

    @Autowired
    private IDataSetService dataSetService;

    @RequestMapping("list")
    public String list(
            @RequestParam(value = "page", required = false, defaultValue = "1") Integer page,
            @RequestParam(value = "size", required = false, defaultValue = "20") Integer size,
            @RequestParam(value = "name", required = false) String name,
            @RequestParam(value = "order", required = false) String order,
            @RequestParam(value = "superOrg", required = false) Integer superOrg
    ) {
        PageResult<Org> pageResult = new PageResult<Org>();
        pageResult.setPage(page);
        pageResult.setSize(size);
        Org org = new Org();

        if (StringUtils.hasLength(name)) {
            org.setName(name);
        }

        if (superOrg != null) {
            org.setSuperOrg(new Org(superOrg));
        }

        if (StringUtils.hasLength(order)) {
            pageResult.setSortBy(order);
            pageResult.setSortColumn("o.name");
        }

        pageResult.setT(org);
        Result<Org> result = service.getByPage(pageResult);

        setRequestAttr("result", result);


        if (result.isSuccess()) {
            setRequestAttr("name", name);
            setRequestAttr("order", order);
            return "/front/front/org/list";
        } else {
            return setRequestForwordAttr("访问发生异常", "访问发生异常，请联系管理员", "/");
        }
    }


    @RequestMapping("view")
    public String detail(
            @RequestParam("id") Integer id
    ) {
        Org org = service.getById(id).getTarget();
        if (org == null) {
            setMessage("访问失败", "该组织不存在");
        }
        DataSet dataSet = new DataSet();
        dataSet.setOrg(new Org(id));
        Result<DataSet> dataSetResult = dataSetService.getList(dataSet);
        setRequestAttr("dataSetResult", dataSetResult);
        setRequestAttr("org", org);

        return "/front/front/org/view";
    }

}

